<?php

/* 店铺控制器 */
class StoreApp extends BackendApp
{
	var $_store_mod;

	function __construct()
	{
		$this->StoreApp();
	}

	function StoreApp()
	{
		parent::__construct();
		$this->_store_mod =& m('store');
	}

	function index()
	{
		$conditions = empty($_GET['wait_verify']) ? "state <> '" . STORE_APPLYING . "'" : "state = '" . STORE_APPLYING . "'";
		$filter = $this->_get_query_conditions(array(
		array(
		'field' => 'store_name',
		'equal' => 'like',
		),
		array(
		'field' => 'sgrade',
		),
		));
		$owner_name = trim($_GET['owner_name']);
		if ($owner_name)
		{

			$filter .= " AND (user_name LIKE '%{$owner_name}%' OR owner_name LIKE '%{$owner_name}%') ";
		}
		//更新排序
		if (isset($_GET['sort']) && isset($_GET['order']))
		{
			$sort  = strtolower(trim($_GET['sort']));
			$order = strtolower(trim($_GET['order']));
			if (!in_array($order,array('asc','desc')))
			{
				$sort  = 'sort_order';
				$order = '';
			}
		}
		else
		{
			$sort  = 'store_id';
			$order = 'desc';
		}

		$this->assign('filter', $filter);
		$conditions .= $filter;
		$page = $this->_get_page();
		$stores = $this->_store_mod->find(array(
		'conditions' => $conditions,
		'join'  => 'belongs_to_user',
		'fields'=> 'this.*,member.user_name',
		'limit' => $page['limit'],
		'count' => true,
		'order' => "$sort $order"
		));
		$sgrade_mod =& m('sgrade');
		$grades = $sgrade_mod->get_options();
		$this->assign('sgrades', $grades);

		$states = array(
		STORE_APPLYING  => LANG::get('wait_verify'),
		STORE_OPEN      => Lang::get('open'),
		STORE_CLOSED    => Lang::get('close'),
		);
                
                include_once ROOT_PATH . "/includes/string.php";
		foreach ($stores as $key => $store)
		{
                        $token = base64_encode(String::authCode($key . "|". $this->visitor->info['user_id'] ."|". $this->visitor->info['user_name'] , 'ENCODE', 'wljiashi', 60*60));
                        $stores[$key]['token'] = $token;
			$stores[$key]['sgrade'] = $grades[$store['sgrade']];
			$stores[$key]['state'] = $states[$store['state']];
			$certs = empty($store['certification']) ? array() : explode(',', $store['certification']);
			for ($i = 0; $i < count($certs); $i++)
			{
				$certs[$i] = Lang::get($certs[$i]);
			}
			$stores[$key]['certification'] = join('<br />', $certs);
		}
                
		$this->assign('stores', $stores);

		$page['item_count'] = $this->_store_mod->getCount();
		$this->import_resource(array('script' => 'inline_edit.js'));
		$this->_format_page($page);
		$this->assign('filtered', $filter? 1 : 0); //是否有查询条件
		$this->assign('page_info', $page);

		$this->display('store.index.html');
	}
	function test()
	{
		if (!IS_POST)
		{
			$sgrade_mod =& m('sgrade');
			$grades = $sgrade_mod->find();
			if (!$grades)
			{
				$this->show_warning('set_grade_first');
				return;
			}
			$this->display('store.test.html');
		}
		else
		{
			$user_name = trim($_POST['user_name']);
			$password  = $_POST['password'];

			/* 连接到用户系统 */
			$ms =& ms();
			$user = $ms->user->get($user_name, true);
			if (empty($user))
			{
				$this->show_warning('user_not_exist');
				return;
			}
			if ($_POST['need_password'] && !$ms->user->auth($user_name, $password))
			{
				$this->show_warning('invalid_password');

				return;
			}

			$store = $this->_store_mod->get_info($user['user_id']);
			if ($store)
			{
				if ($store['state'] == STORE_APPLYING)
				{
					$this->show_warning('user_has_application');
					return;
				}
				else
				{
					$this->show_warning('user_has_store');
					return;
				}
			}
			else
			{
				header("Location:index.php?app=store&act=add&user_id=" . $user['user_id']);
			}
		}
	}

	function add()
	{
		$user_id = $_GET['user_id'];
		if (!$user_id)
		{
			$this->show_warning('Hacking Attempt');
			return;
		}

		if (!IS_POST)
		{
			/* 取得会员信息 */
			include_once(ROOT_PATH . '/includes/cfg_status.php');
			$user_mod =& m('member');
			$user = $user_mod->get_info($user_id);
			$this->assign('user', $user);

			$this->assign('store', array('state' => STORE_OPEN, 'recommended' => 0, 'sort_order' => 65535, 'end_time' => 0));

			$sgrade_mod =& m('sgrade');
			$this->assign('sgrades', $sgrade_mod->get_options());

			$this->assign('states', array(
			STORE_OPEN   => Lang::get('open'),
			STORE_CLOSED => Lang::get('close'),
			));

			$this->assign('recommended_options', array(
			'1' => Lang::get('yes'),
			'0' => Lang::get('no'),
			));

//			$this->assign('scategories', $this->_get_scategory_options());

			$region_mod =& m('region');
			$this->assign('regions', $region_mod->get_options(0));

			/* 导入jQuery的表单验证插件 */
			$this->import_resource(array(
			'script' => 'jquery.plugins/jquery.validate.js,mlselection.js'
			));
			$this->assign('enabled_subdomain', ENABLED_SUBDOMAIN);
			$this->assign('cfg_store_pay_type', $cfg_store_pay_type);
			$this->display('store.form.html');
		}
		else
		{
			/* 检查名称是否已存在 */
			if (!$this->_store_mod->unique(trim($_POST['store_name'])))
			{
				$this->show_warning('name_exist');
				return;
			}
			$domain = empty($_POST['domain']) ? '' : trim($_POST['domain']);
			if (!$this->_store_mod->check_domain($domain, Conf::get('subdomain_reserved'), Conf::get('subdomain_length')))
			{
				$this->show_warning($this->_store_mod->get_error());

				return;
			}
            if($_POST['sgrade'] == 2)
            {
                if(floatval($_POST['proportion']) <= 0)
                {
                    $this->show_warning('请填写佣金比例');

                    return;
                }

            }

			$data = array(
			'store_id'     => $user_id,
			'store_name'   => $_POST['store_name'],
			'owner_name'   => $_POST['owner_name'],
			'pay_account_name' => html_script(trim($_POST['pay_account_name'])),
			'pay_account' => html_script(trim($_POST['pay_account'])),
			'pay_bank' => html_script(trim($_POST['pay_bank'])),
			'pay_invoice' => html_script(trim($_POST['pay_invoice'])),
			'pay_type' => html_script(trim($_POST['pay_type'])),
			'owner_card'   => $_POST['owner_card'],
			'region_id'    => $_POST['region_id'],
			'region_name'  => $_POST['region_name'],
			'address'      => $_POST['address'],
			'zipcode'      => $_POST['zipcode'],
			'tel'          => $_POST['tel'],
			'sgrade'       => $_POST['sgrade'],
			'end_time'     => empty($_POST['end_time']) ? 0 : gmstr2time(trim($_POST['end_time'])),
			'state'        => $_POST['state'],
			'recommended'  => $_POST['recommended'],
			'sort_order'   => $_POST['sort_order'],
			'add_time'     => gmtime(),
			'domain'       => $domain,
			'proportion'   => $_POST['sgrade'] == 2 ? floatval($_POST['proportion']) : 0,
			);
			$certs = array();
			isset($_POST['autonym']) && $certs[] = 'autonym';
			isset($_POST['material']) && $certs[] = 'material';
			$data['certification'] = join(',', $certs);

			if ($this->_store_mod->add($data) === false)
			{
				$this->show_warning($this->_store_mod->get_error());
				return false;
			}

//			$this->_store_mod->unlinkRelation('has_scategory', $user_id);
			$cate_id = intval($_POST['cate_id']);
			if ($cate_id > 0)
			{
//				$this->_store_mod->createRelation('has_scategory', $user_id, $cate_id);
			}

			$this->admin_log(Lang::get('add').Lang::get('store').':'.$data['store_name']);
			$this->show_message('add_ok',
			'back_list',    'index.php?app=store',
			'continue_add', 'index.php?app=store&amp;act=test'
			);
		}
	}

	function edit()
	{
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!IS_POST)
		{
			/* 是否存在 */
			include_once(ROOT_PATH . '/includes/cfg_status.php');
			$store = $this->_store_mod->get_info($id);
			if (!$store)
			{
				$this->show_warning('store_empty');
				return;
			}
			if ($store['certification'])
			{
				$certs = explode(',', $store['certification']);
				foreach ($certs as $cert)
				{
					$store['cert_' . $cert] = 1;
				}
			}
			$this->assign('store', $store);

			$sgrade_mod =& m('sgrade');
			$this->assign('sgrades', $sgrade_mod->get_options());

			$this->assign('states', array(
			STORE_OPEN   => Lang::get('open'),
			STORE_CLOSED => Lang::get('close'),
			));

			$this->assign('recommended_options', array(
			'1' => Lang::get('yes'),
			'0' => Lang::get('no'),
			));

			$region_mod =& m('region');
			$this->assign('regions', $region_mod->get_options(0));

//			$this->assign('scategories', $this->_get_scategory_options());

//			$scates = $this->_store_mod->getRelatedData('has_scategory', $id);
//			$this->assign('scates', array_values($scates));

			/* 导入jQuery的表单验证插件 */
			$this->import_resource(array(
			'script' => 'jquery.plugins/jquery.validate.js,mlselection.js'
			));
			$this->assign('enabled_subdomain', ENABLED_SUBDOMAIN);
			$this->assign('cfg_store_pay_type', $cfg_store_pay_type);
			$this->display('store.form.html');
		}
		else
		{
			/* 检查名称是否已存在 */
			if (!$this->_store_mod->unique(trim($_POST['store_name']), $id))
			{
				$this->show_warning('name_exist');
				return;
			}
			$store_info = $this->_store_mod->get_info($id);
			$domain = empty($_POST['domain']) ? '' : trim($_POST['domain']);
			if ($domain && $domain != $store_info['domain'])
			{
				if (!$this->_store_mod->check_domain($domain, Conf::get('subdomain_reserved'), Conf::get('subdomain_length')))
				{
					$this->show_warning($this->_store_mod->get_error());

					return;
				}
			}

            if($_POST['sgrade'] == 2)
            {
                if(floatval($_POST['proportion']) <= 0)
                {
                    $this->show_warning('请填写佣金比例');

                    return;
                }

            }

			$data = array(
			'store_name'   => $_POST['store_name'],
			'owner_name'   => $_POST['owner_name'],
			'pay_account_name' => html_script(trim($_POST['pay_account_name'])),
			'pay_account' => html_script(trim($_POST['pay_account'])),
			'pay_bank' => html_script(trim($_POST['pay_bank'])),
			'pay_invoice' => html_script(trim($_POST['pay_invoice'])),
			'pay_type' => html_script(trim($_POST['pay_type'])),
			'owner_card'   => $_POST['owner_card'],
			'region_id'    => $_POST['region_id'],
			'region_name'  => $_POST['region_name'],
			'address'      => $_POST['address'],
			'zipcode'      => $_POST['zipcode'],
			'tel'          => $_POST['tel'],
			'sgrade'       => $_POST['sgrade'],
			'end_time'     => empty($_POST['end_time']) ? 0 : gmstr2time(trim($_POST['end_time'])),
			'state'        => $_POST['state'],
			'sort_order'   => $_POST['sort_order'],
			'recommended'  => $_POST['recommended'],
			'domain'       => $domain,
            'proportion'       => $_POST['sgrade'] == 2 ? floatval($_POST['proportion']) : 0,
			);
			$data['state'] == STORE_CLOSED && $data['close_reason'] = $_POST['close_reason'];
			$certs = array();
			isset($_POST['autonym']) && $certs[] = 'autonym';
			isset($_POST['material']) && $certs[] = 'material';
			$data['certification'] = join(',', $certs);

			$old_info = $this->_store_mod->get_info($id); // 修改前的店铺信息
			$this->_store_mod->edit($id, $data);

			$this->_store_mod->unlinkRelation('has_scategory', $id);
			$cate_id = intval($_POST['cate_id']);
			if ($cate_id > 0)
			{
				$this->_store_mod->createRelation('has_scategory', $id, $cate_id);
			}

			/* 如果修改了店铺状态，通知店主 */
			if ($old_info['state'] != $data['state'])
			{
				$ms =& ms();
				if ($data['state'] == STORE_CLOSED)
				{
					// 关闭店铺
					$this->admin_log(Lang::get('close').Lang::get('store').':'.$data['store_name']);
					$subject = Lang::get('close_store_notice');
					//$content = sprintf(Lang::get(), $data['close_reason']);
					$content = get_msg('toseller_store_closed_notify',array('reason' => $data['close_reason']));
				}
				else
				{
					// 开启店铺
					$this->admin_log(Lang::get('open').Lang::get('store').':'.$data['store_name']);
					$subject = Lang::get('open_store_notice');
					$content = Lang::get('toseller_store_opened_notify');
				}
				$ms->pm->send(MSG_SYSTEM, $old_info['store_id'], '', $content);
				$this->_mailto($old_info['email'], $subject, $content);
			}

			$ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
			$this->admin_log(Lang::get('edit').Lang::get('store').':'.$data['store_name']);
			$this->show_message('edit_ok',
			'back_list',    'index.php?app=store&page=' . $ret_page,
			'edit_again',   'index.php?app=store&amp;act=edit&amp;id=' . $id
			);
		}
	}

	//异步修改数据
	function ajax_col()
	{
		$id     = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$column = empty($_GET['column']) ? '' : trim($_GET['column']);
		$value  = isset($_GET['value']) ? trim($_GET['value']) : '';
		$data   = array();
		if (in_array($column ,array('recommended','sort_order')))
		{
			$data[$column] = $value;
			$this->_store_mod->edit($id, $data);
			if(!$this->_store_mod->has_error())
			{
				$this->admin_log(Lang::get('edit').Lang::get('store').':'.$this->_store_mod->get_fields_name($id,'store_name'));
				echo ecm_json_encode(true);
			}
		}
		else
		{
			return ;
		}
		return ;
	}

	function drop()
	{
		$id = isset($_GET['id']) ? trim($_GET['id']) : '';
		if (!$id)
		{
			$this->show_warning('no_store_to_drop');
			return;
		}

		$ids = explode(',', $id);
		foreach ($ids as $id)
		{
			$this->_drop_store_image($id); // 注意这里要先删除图片，再删除店铺，因为删除图片时要查店铺信息

		}
		$this->admin_log(Lang::get('drop').Lang::get('store').':'.$id);

		if (!$this->_store_mod->drop($ids))
		{
			$this->show_warning($this->_store_mod->get_error());
			return;
		}

		/* 通知店主 */
		$user_mod =& m('member');
		$users = $user_mod->find(array(
		'conditions' => "user_id" . db_create_in($ids),
		'fields'     => 'user_id, user_name, email',
		));
		foreach ($users as $user)
		{
			$ms =& ms();
			$subject = Lang::get('drop_store_notice');
			$content = get_msg('toseller_store_droped_notify');
			$ms->pm->send(MSG_SYSTEM, $user['user_id'], $subject, $content);
			$this->_mailto($user['email'], $subject, $content);
		}

		$this->show_message('drop_ok');
	}

	/* 更新排序 */
	function update_order()
	{
		if (empty($_GET['id']))
		{
			$this->show_warning('Hacking Attempt');
			return;
		}

		$ids = explode(',', $_GET['id']);
		$sort_orders = explode(',', $_GET['sort_order']);
		foreach ($ids as $key => $id)
		{
			$this->_store_mod->edit($id, array('sort_order' => $sort_orders[$key]));
		}

		$this->show_message('update_order_ok');
	}

	/* 查看并处理店铺申请 */
	function view()
	{
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!IS_POST)
		{
			/* 是否存在 */
			$store = $this->_store_mod->get_info($id);
			if (!$store)
			{
				$this->show_warning('Hacking Attempt');
				return;
			}

			$sgrade_mod =& m('sgrade');
			$sgrades = $sgrade_mod->get_options();
			$store['sgrade'] = $sgrades[$store['sgrade']];
			$this->assign('store', $store);

			$scates = $this->_store_mod->getRelatedData('has_scategory', $id);
			$this->assign('scates', $scates);

			$this->display('store.view.html');
		}
		else
		{
			$ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
			/* 批准 */
			if (isset($_POST['agree']))
			{
				$this->_store_mod->edit($id, array(
				'state'      => STORE_OPEN,
				'add_time'   => gmtime(),
				'sort_order' => 65535,
				));

				$content = get_msg('toseller_store_passed_notify');
				$ms =& ms();
				$ms->pm->send(MSG_SYSTEM, $id, '', $content);
				$store_info = $this->_store_mod->get_info($id);
				$this->send_feed('store_created', array(
				'user_id'   =>  $store_info['store_id'],
				'user_name'   => $store_info['user_name'],
				'store_url'   => SITE_URL . '/' . url('app=store&id=' . $store_info['store_id']),
				'seller_name'   => $store_info['store_name'],
				));
				$this->_hook('after_opening', array('user_id' => $id));

				$this->admin_log(Lang::get('agree').'"'.$store_info['user_name'].'"'.Lang::get('open').Lang::get('store').':'.$store_info['store_name']);
				$this->show_message('agree_ok',
				'edit_the_store', 'index.php?app=store&amp;act=edit&amp;id=' . $id,
				'back_list', 'index.php?app=store&wait_verify=1&page=' . $ret_page
				);
			}
			/* 拒绝 */
			elseif (isset($_POST['reject']))
			{
				$reject_reason = trim($_POST['reject_reason']);
				if (!$reject_reason)
				{
					$this->show_warning('input_reason');
					return;
				}

				$content = get_msg('toseller_store_refused_notify', array('reason' => $reject_reason));
				$ms =& ms();
				$ms->pm->send(MSG_SYSTEM, $id, '', $content);

				$store_info = $this->_store_mod->get_info($id);
				$this->admin_log(Lang::get('reject').'"'.$store_info['user_name'].'"'.Lang::get('open').Lang::get('store').':'.$store_info['store_name']);
				$this->_drop_store_image($id); // 注意这里要先删除图片，再删除店铺，因为删除图片时要查店铺信息
				$this->_store_mod->drop($id);
				$this->show_message('reject_ok',
				'back_list', 'index.php?app=store&wait_verify=1&page=' . $ret_page
				);
			}
			else
			{
				$this->show_warning('Hacking Attempt');
				return;
			}
		}
	}
        
        //编辑店铺会员的操作权限
        function edit_priv()
        {
            $id = (isset($_GET['id']) && $_GET['id'] !='') ? intval($_GET['id']) : '';
            $admin_mod = & m('userpriv');
            
            if (!IS_POST)
            {
                $store = $this->_store_mod->get_info($id);
                if (!$store)
                {
                        $this->show_warning('store_empty');
                        return;
                }
                //获取当前管理员权限
                $privs = $admin_mod->get(array(
                    'conditions' => '1=1 AND  store_id =' . $id . ' AND user_id = '.$id,
                    'fields' => 'privs2',
                ));
                
                $priv=explode(',', $privs['privs2']);
                $priv_data = include_once(ROOT_PATH.'/wl_admin/includes/store.priv.inc.php');
                $this->assign('store',$store);
                $this->assign('checked_priv',$priv);
                $this->assign('priv',$priv_data);
                $this->display('store.priv.form.html');
            }else
            {
                //更新权限
                $privs = (isset($_POST['priv']) && $_POST['priv']!='priv') ? $_POST['priv']: '';
                $priv = '';
                if ($privs)
                {
                    $priv = implode(',', array_unique($privs));
                }
                
                $data = array(
                        'user_id' => $id,
                        'store_id' => $id,
                        'privs2' => $priv,
                   );
                $admin_mod->edit("store_id ='{$id}' AND user_id = '{$id}'", $data);
                if($admin_mod->has_error())
                {
                     $this->show_warning($admin_mod->get_error());
                     return;
                 }
                 else
                {
                    $this->admin_log("修改店铺{$id}的权限");
                    $this->show_message('权限修改成功');
                    return true;
                 }
            }
        }

	function batch_edit()
	{
		if (!IS_POST)
		{
			$sgrade_mod =& m('sgrade');
			$this->assign('sgrades', $sgrade_mod->get_options());

			$region_mod =& m('region');
			$this->assign('regions', $region_mod->get_options(0));

			$this->headtag('<script type="text/javascript" src="{lib file=mlselection.js}"></script>');
			$this->display('store.batch.html');
		}
		else
		{
			$id = isset($_POST['id']) ? trim($_POST['id']) : '';
			if (!$id)
			{
				$this->show_warning('Hacking Attempt');
				return;
			}

			$ids = explode(',', $id);
			$data = array();
			if ($_POST['region_id'] > 0)
			{
				$data['region_id'] = $_POST['region_id'];
				$data['region_name'] = $_POST['region_name'];
			}
			if ($_POST['sgrade'] > 0)
			{
				$data['sgrade'] = $_POST['sgrade'];
			}
			if ($_POST['certification'])
			{
				$certs = array();
				if ($_POST['autonym'])
				{
					$certs[] = 'autonym';
				}
				if ($_POST['material'])
				{
					$certs[] = 'material';
				}
				$data['certification'] = join(',', $certs);
			}
			if ($_POST['recommended'] > -1)
			{
				$data['recommended'] = $_POST['recommended'];
			}
			if (trim($_POST['sort_order']))
			{
				$data['sort_order'] = intval(trim($_POST['sort_order']));
			}

			if (empty($data))
			{
				$this->show_warning('no_change_set');
				return;
			}

			if($ids)
			{
				foreach($ids as $cid)
				{
					$this->admin_log(Lang::get('edit').Lang::get('store').':'.$this->_store_mod->get_fields_name($id,'store_name'));
				}

			}

			$this->_store_mod->edit($ids, $data);
			$ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
			$this->show_message('edit_ok',
			'back_list', 'index.php?app=store&page=' . $ret_page);
		}
	}

	function check_name()
	{
		$id         = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$store_name = empty($_GET['store_name']) ? '' : trim($_GET['store_name']);

		if (!$this->_store_mod->unique($store_name, $id))
		{
			echo ecm_json_encode(false);
			return;
		}
		echo ecm_json_encode(true);
	}
        
        function into_seller()
        {
            header("Location:" . SITE_URL . "/index.php?app=member&act=login&token=" . $_GET['token']);
        }

	/* 删除店铺相关图片 */
	function _drop_store_image($store_id)
	{
		$files = array();

		/* 申请店铺时上传的图片 */
		$store = $this->_store_mod->get_info($store_id);
		for ($i = 1; $i <= 3; $i++)
		{
			if ($store['image_' . $i])
			{
				$files[] = $store['image_' . $i];
			}
		}

		/* 店铺设置中的图片 */
		if ($store['store_banner'])
		{
			$files[] = $store['store_banner'];
		}
		if ($store['store_logo'])
		{
			$files[] = $store['store_logo'];
		}

		/* 删除 */
		foreach ($files as $file)
		{
			$filename = ROOT_PATH . '/' . $file;
			if (file_exists($filename))
			{
				@unlink($filename);
			}
		}
	}

	/* 取得店铺分类 */
	function _get_scategory_options()
	{
		$mod =& m('scategory');
		$scategories = $mod->get_list();
		import('tree.lib');
		$tree = new Tree();
		$tree->setTree($scategories, 'cate_id', 'parent_id', 'cate_name');

		return $tree->getOptions();
	}
}

?>
